import time
import sys
from alg import Solution
from gen import generate_test_cases

def test_find_kth_largest():
    """
    测试寻找数组中第K个最大元素算法，并记录每个测试用例的运行时间
    结果将输出到test.txt文件中
    """
    solution = Solution()
    test_cases = generate_test_cases()
    
    # 创建并打开test.txt文件用于写入结果
    with open('test.txt', 'w', encoding='utf-8') as f:
        f.write("数组中第K个最大元素算法性能测试\n")
        f.write("-" * 70 + "\n")
        f.write(f"{'测试用例':^10}{'描述':^30}{'结果':^15}{'运行时间 (ms)':^15}\n")
        f.write("-" * 70 + "\n")
        
        total_time = 0
        
        for i, (nums, k, desc) in enumerate(test_cases, 1):
            # 复制数组以防止算法修改原数组
            nums_copy = nums.copy()
            
            start_time = time.time()
            result = solution.findKthLargest(nums_copy, k)
            end_time = time.time()
            
            execution_time = (end_time - start_time) * 1000  # 转换为毫秒
            total_time += execution_time
            
            f.write(f"{i:^10}{desc:^30}{result:^15}{execution_time:.3f}ms\n")
            
            # 输出详细信息
            if len(nums) <= 20:  # 只打印较短的数组
                f.write(f"  nums: {nums}\n")
            else:
                f.write(f"  nums: [{nums[0]}, {nums[1]}, ..., {nums[-2]}, {nums[-1]}] (长度: {len(nums)})\n")
            f.write(f"  k: {k}\n")
            f.write("\n")
        
        f.write("-" * 70 + "\n")
        f.write(f"总测试用例: {len(test_cases)}\n")
        f.write(f"总运行时间: {total_time:.3f}ms\n")
        f.write(f"平均运行时间: {total_time / len(test_cases):.3f}ms\n")
    
    print(f"测试完成，结果已保存到test.txt文件中")

if __name__ == "__main__":
    test_find_kth_largest()